package indi.defoliation.unknownrpg.api.lore.loretable;

import java.util.ArrayList;
import java.util.List;

import org.bukkit.inventory.ItemStack;

import indi.defoliation.unknownrpg.api.RPGItem;
import indi.defoliation.unknownrpg.api.RPGItemFactory;
import indi.defoliation.unknownrpg.api.config.LoreYamlConfig;
import indi.defoliation.unknownrpg.api.lore.AttributeLoreManager;
import indi.defoliation.unknownrpg.core.attribute.LoreAttribute;
import team.unstudio.udpl.nms.NmsHelper;
import team.unstudio.udpl.nms.inventory.NmsItemStack;
import team.unstudio.udpl.nms.nbt.NBTTagCompound;


public class NBTLoreTable implements LoreTable {

	public static final String LORE_TABLE_NBT_HEAD = "RPG_LORE_TABLE_";

	private static final String HEAD = "head";

	private static final String LENGTH = "length";

	public static ItemStack saveHead(ItemStack item,int head) {
		return setInt(item,HEAD,head);
	}

	public static ItemStack saveLength(ItemStack item,int length) {
		return setInt(item,LENGTH,length);
	}
	
	public static ItemStack removeNBT(ItemStack item) {
		NmsItemStack nmsItem = NmsHelper.createNmsItemStack(item);
		NBTTagCompound tag = nmsItem.getTag();
		tag.remove(LORE_TABLE_NBT_HEAD+HEAD);
		tag.remove(LORE_TABLE_NBT_HEAD+LENGTH);
		nmsItem.setTag(tag);
		return nmsItem.getBukkitItemStack();
	}

	private static ItemStack setInt(ItemStack item,String key,int value) {
		NmsItemStack nmsItem = NmsHelper.createNmsItemStack(item);
		NBTTagCompound tag = nmsItem.getTag();
		tag.setInt(LORE_TABLE_NBT_HEAD+key, value);
		nmsItem.setTag(tag);
		return nmsItem.getBukkitItemStack();
	}

	@Override
	public int getHead(ItemStack item) {
		return getInt(item,HEAD);
	}

	@Override
	public int getLength(ItemStack item) {
		int length = getInt(item,LENGTH);
		if(length==-1)length++;
		return length;
	}

	private int getInt(ItemStack item,String key) {
		NmsItemStack nmsItem = NmsHelper.createNmsItemStack(item);
		NBTTagCompound tag = nmsItem.getTag();
		if(!tag.contain(key))return -1;
		return tag.getInt(LORE_TABLE_NBT_HEAD+key);
	}

	@Override
	public List<String> getLore(ItemStack item) {
		RPGItem rpgItem = RPGItemFactory.getRPGItem(item);
		List<String> lore = new ArrayList<>();
		if(!rpgItem.hasAttribute("Lore"))
			return lore;
		LoreAttribute loreAttribute = (LoreAttribute) rpgItem.getAttribute("Lore");
		lore = LoreYamlConfig.getLore(loreAttribute.getLoreName());
		AttributeLoreManager.replace(lore);
		setHeadAndLength(item,lore.size());
		return lore;
	}
	
	private void setHeadAndLength(ItemStack item,int length) {
		List<String> lore = item.getItemMeta().getLore();
		if(lore==null||lore.isEmpty())
			saveHead(item,0);
		saveHead(item,lore.size());
		saveLength(item,length);
	}

	@Override
	public ItemStack removeLore(ItemStack item) {
		return removeNBT(LoreHelper.removeItemLoreText(item, this));
	}

}